Empresas
Empregos
  • Sobre nós
  • Soluções
    • Publicação de vagas
      Publique sua vaga e receba candidatos qualificados em 48h.
    • Avaliações de candidatos
      Mais de 500 testes técnicos e psicológicos, mais anti-fraude.
    • Headhunting
      Busca executiva personalizada do início ao fim.
    • Folha de Pagamento + EOR
      Dispersão de folha e EOR em mais de 15 países da LATAM.
  • Preços
  • Empregos

0

427
Visualizações
Why do I get "Invalid Form Body" when trying to embed a local image in a message?

Right now I'm working on making a bot that will post a random image from a local folder on my VSC. However, posting an embed message with the image results in an error:

DiscordAPIError: Invalid Form Body embeds[0].image.url: Could not interpret "{'attachment': ['1.jpg', '2mkjR-3__400x400.jpg', '8921036_sa.jpg', '91Vk1mS1x3L.png'], 'name': None}" as string.

This can be reproduced with the sample code:

const Discord = require('discord.js');
const { Intents } = Discord;
const fs = require('fs');

const config = require('config');
const authToken = config.get('authToken');

const myIntents = new Intents([
    Intents.FLAGS.GUILDS,
    Intents.FLAGS.GUILD_MESSAGES
]);
const client = new Discord.Client({ intents: myIntents });

client.on("ready", (client) => {
    console.log(`Logged in as ${client.user.tag}.`);
});

client.on("messageCreate", (message) => {
    if ('.pic' === message.content) {
        let files = fs.readdirSync('./assets/images/');
        let chosenFile = files[Math.floor(Math.random() * files.length)];
        const image = new Discord.MessageAttachment(files);
        const embed = new Discord.MessageEmbed()
              .setTitle('yeet')
              .setImage(image)
              .setFooter('By K4STOR','');
        message.channel.send({embeds: [embed]});
    }
});

client.login(authToken);

In addition to the above script, you'll need to:

  • create an 'assets/images' directory and
  • add at least one image;
  • create a configuration file (e.g. 'config/local.json') and
  • add an appropriate 'authToken' entry

How can the above code be fixed to send the image?

about 4 years ago · Juan Pablo Isaza
2 Respostas
Responde à pergunta

0

Try this:

var fs = require('fs');

client.on("ready", () => {
    
    console.log("Why did I make this...")

    command(client, 'pic', (message) => {
        //choose one file from folder "./images" randomly
        var files = fs.readdirSync("./images/")
        let chosenFile = files[Math.floor(Math.random() * files.length)]
 
        //create embed and use image from messageAttachments
        const embed = new Discord.MessageEmbed()
            .setTitle('yeet')
            .setImage(`attachment://${chosenFile}`)
            .setFooter('By K4STOR','')

        //discord.js V13 variant of sending embeds
        //necessary to set files, otherwise #setImage with localfile does not work
        message.channel.send({
          embeds: [embed], 
          files: [`./images/${chosenFile}`]
        });
    })
})

about 4 years ago · Juan Pablo Isaza Relatório

0

Main Issue

MessageEmbed.setImage() takes a URL, not a MessageAttachment. For attachments, you must pass them via the files option TextChannel.send(). Note the guide on attaching images to an embed message shows this.

Additionally, the path to the image directory must be combined with the chosen file name when the attachment object is created.

Minor issue

Note that all images appear in the error message. This is due to a minor issue: the attachment is set to files, rather than chosenFile. Note this sort of issue is considered on SO.

Changes

Just these changes would look like:

const path = require('path');
...
const imgDir = './assets/images/';
...
        const image = new Discord.MessageAttachment(
            path.join(imgDir, chosenFile),
            chosenFile,
            {url: 'attachment://' + chosenFile});
        const embed = new Discord.MessageEmbed()
              .setImage(image.url)
              ...
        
        message.channel.send({embeds: [embed], files: [image]});

Full Sample

The sample with the above changes applied would be:

const Discord = require('discord.js');
const { Intents } = Discord;
const fs = require('fs');
const path = require('path');

const config = require('config');
const authToken = config.get('authToken');

const myIntents = new Intents([
    Intents.FLAGS.GUILDS,
    Intents.FLAGS.GUILD_MESSAGES
]);
const client = new Discord.Client({ intents: myIntents });

client.on("ready", (client) => {
    console.log(`Logged in as ${client.user.tag}.`);
});

const imgDir = './assets/images/';
client.on("messageCreate", (message) => {
    if ('.pic' === message.content) {
        let files = fs.readdirSync(imgDir);
        let chosenFile = files[Math.floor(Math.random() * files.length)];
        const image = new Discord.MessageAttachment(
            path.join(imgDir, chosenFile),
            chosenFile,
            {url: 'attachment://' + chosenFile});
        const embed = new Discord.MessageEmbed()
              .setTitle('yeet')
              .setImage(image.url)
              .setFooter('By K4STOR','');
        console.log(`Sending ${chosenFile}.`);
        message.channel.send({embeds: [embed], files: [image]});
    }
});

client.login(authToken);
about 4 years ago · Juan Pablo Isaza Relatório
Responde à pergunta
Encontrar trabalhos remotos

Descubra a nova forma de encontrar um emprego!

melhores empregos
Principais categorias de trabalho
Empresas
Postar vaga Preços Comercial
Jurídico
Termos e Condições Política de privacidade
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomende algumas ofertas para mim
Preciso de ajuda